package RootDNSServer;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.List;

/**
 * @Author: 0162977
 * @Date: 2020/12/3 15:41
 */
public class ListenThread  implements Runnable{

    DatagramSocket socket = null;
    DatagramPacket packet = null;

    public ListenThread(DatagramSocket socket,DatagramPacket packet) {
        this.socket = socket;
        this.packet = packet;
    }

    @Override
    public void run() {
        String info = null;
        DatagramPacket packet2 = null;
        info = new String(packet.getData(), 0, packet.getLength());
        System.out.println(info);
        try {
            switch (info.split(",")[0]) {
                case "1": {   //第一个字符是1，代表是查询请求（递归式）
                    String website = info.split(",")[1];   //获取要解析的域名
                    String portReq = info.split(",")[2];
                    if (ShareSpaceAndFun.addWait(website, Integer.parseInt(portReq))) {  //加入等待队列
                        //转发顶级服务器
                        InetAddress address = InetAddress.getByName("localhost");

                        byte[] data2 = ("1," + website + "," + ShareSpaceAndFun.myPort).getBytes();
                        packet2 = new DatagramPacket(data2, data2.length, address, ShareSpaceAndFun.portTop);
                        socket.send(packet2);
                    }

                    break;
                }
                case "0": {   //第一个字符是0，代表是查询结果
                    String website = info.split(",")[1];   //获取要解析的域名

                    InetAddress address = null;
                    address = InetAddress.getByName("localhost");

                    List<Integer> portWaitList = ShareSpaceAndFun.getWaitPortByWebsite(website);
                    if (portWaitList != null) {
                        for (Integer port : portWaitList) {
                            //发回客户端

                            byte[] data2 = info.getBytes();
                            packet2 = new DatagramPacket(data2, data2.length, address, port);
                            socket.send(packet2);
                        }
                    }

                    break;
                }
                case "2": {   //第一个字符是2，代表是迭代式查询
                    String website = info.split(",")[1];   //获取要解析的域名
                    String portNext =  info.split(",")[2];
                    //转发本地服务器
                    InetAddress address = null;
                    address = InetAddress.getByName("localhost");

                    byte[] data2 = ("2," + website + "," + ShareSpaceAndFun.portTop).getBytes();
                    packet2 = new DatagramPacket(data2, data2.length, address, Integer.parseInt(portNext));
                    socket.send(packet2);
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}